#!/bin/bash

INDEX=$2

RUN_DIR=/var/vcap/sys/run/director
LOG_DIR=/var/vcap/sys/log/director
PIDFILE=$RUN_DIR/worker_$INDEX.pid
RUNAS=vcap

# Postgres
POSTGRES_PACKAGE="postgres-13"
PATH=/var/vcap/packages/${POSTGRES_PACKAGE}/bin:$PATH
LD_LIBRARY_PATH=/var/vcap/packages/libpq/lib:$LD_LIBRARY_PATH

# MySQL
PATH=/var/vcap/packages/mysql/bin:$PATH
LD_LIBRARY_PATH=/var/vcap/packages/mysql/lib/mysql:$LD_LIBRARY_PATH

source /var/vcap/jobs/director/env

PATH=$PATH:/var/vcap/jobs/director/bin
export PATH LD_LIBRARY_PATH
export LANG=en_US.UTF-8


export TMPDIR=/var/vcap/data/director/tmp

export QUEUE="normal,urgent"
<% if (p('director.enable_dedicated_status_worker')) && (p('director.workers') > 1) %>
if [ $INDEX -eq 1 ]; then
  export QUEUE="urgent"
fi
<% end %>

# previous value was 16777216, lowered because of: https://bugs.ruby-lang.org/issues/17583
export RUBY_THREAD_VM_STACK_SIZE=15000000
export RUBY_THREAD_MACHINE_STACK_SIZE=15000000

DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
source $DIR/ps_utils.sh

case $1 in

  start)
    mkdir -p $RUN_DIR $LOG_DIR $TMPDIR
    chown -R $RUNAS:$RUNAS $RUN_DIR $LOG_DIR $TMPDIR

    echo $$ > $PIDFILE

    exec chpst -u $RUNAS:$RUNAS \
      /var/vcap/packages/director/bin/bosh-director-worker \
      -c /var/vcap/jobs/director/config/director.yml -i $INDEX \
      >>$LOG_DIR/worker_$INDEX.stdout.log \
      2>>$LOG_DIR/worker_$INDEX.stderr.log
    ;;

  stop)
    PID=$(head -1 $PIDFILE)
    kill_process $PID # prevent the parent from fork()ing new children
    for CHILD in $(list_child_processes $INDEX); do
      kill_process $CHILD
    done
    rm -f $PIDFILE
    ;;

  *)
  echo "Usage: worker_ctl {start|stop}" ;;
esac
exit 0
